import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MyByteParser{
	
	private DataFileStorer fileStorer;

	public MyByteParser(DataFileStorer fileStorer) {
		this.fileStorer = fileStorer;
	}


	public void process(InputStream inputStream) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			
			Data data = null;
			
			String line;
			//Skip the first xml specification line
			reader.readLine();	
			int valueCounter = 0;
			
			String weatherDataBeginTag = "<WEATHERDATA>";
			String weatherDataEndTag = "</WEATHERDATA>";
			String measurementBeginTag = "<MEASUREMENT>";
			String measurementEndTag = "</MEASUREMENT>";
			
			Boolean ignoreFirstLine = true;
			
			while((line = reader.readLine()) != null){
				if(ignoreFirstLine){
					line = reader.readLine();
					ignoreFirstLine = false;
				}				
				line = line.trim();				
				if(line.equalsIgnoreCase(measurementBeginTag)){
					data = new Data();
				}
				else if(line.equalsIgnoreCase(measurementEndTag)){						
					//add data to buffer of filewriter
					fileStorer.addToBuffer(data);					
					
					//Reset all values for next client
					data = null;
					valueCounter = 0;
					
				}				
				else if(line.equalsIgnoreCase(weatherDataBeginTag)){
					
				}
				else if(line.equalsIgnoreCase(weatherDataEndTag)){
					ignoreFirstLine = true;
				}			
				else{
					switch(valueCounter){
						case 0:
							data.setStn(Integer.parseInt(getValue(line, 5)));
						break;
						case 1:
							data.setDate(getValue(line, 6));
						break;
						case 2:
							data.setTime(getValue(line, 6));
						break;
						case 3:
							data.setTemp(Double.parseDouble(getValue(line, 6)));
						break;
						case 4:
							data.setDewp(Double.parseDouble(getValue(line, 6)));
						break;
						case 5:
							data.setStp(Double.parseDouble(getValue(line, 5)));
						break;
						case 6:
							data.setSlp(Double.parseDouble(getValue(line, 5)));
						break;
						case 7:
							data.setVisib(Double.parseDouble(getValue(line, 7)));
						break;
						case 8:
							data.setWdsp(Double.parseDouble(getValue(line, 6)));
						break;
						case 9:
							data.setPrcp(Double.parseDouble(getValue(line, 6)));
						break;
						case 10:
							data.setSndp(Double.parseDouble(getValue(line, 6)));
						break;
						case 11:
							data.setFrshtt(getValue(line, 8));
						break;
						case 12:
							data.setCldc(Double.parseDouble(getValue(line, 6)));
						break;
						case 13:
							data.setWnddir(Integer.parseInt(getValue(line, 8)));
						break;
					}					
					valueCounter++;
				}	
			}
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public String getValue(String line, int lengthOfTag){
		String value = line.substring(lengthOfTag, line.length() - (lengthOfTag+1));
		if(value == ""){
			value = "0";
		}
		if(value.trim().isEmpty()){
			value="0";
		}
		return value;
	}

}

